//
//  NSString+Extensoin.m
//  MyShoppingApp
//
//  Created by Mac on 16/1/16.
//  Copyright © 2016年 ibokan. All rights reserved.
//

#import "NSString+Extensoin.h"
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (Extensoin)
//文本的自适应
- (CGRect)textRectWithSize:(CGSize)size fontSize:(CGFloat)fontSize
{
    return [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil];
}

//计算字符串除空格的长度
+ (NSUInteger)whiteString:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return string.length;
}

//获取字符串的宽度
+(float) widthForString:(NSString *)value fontSize:(float)fontSize andHeight:(float)height
{
    CGRect rect = [value boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)  options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil];
    
    return rect.size.width;
}
//获取字符串的宽度
+(float) widthForString:(NSString *)value UIfontSize:(UIFont *)fontSize andHeight:(float)height
{
    CGRect rect = [value boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height)  options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:fontSize} context:nil];
    
    return rect.size.width;
}

//获得字符串的高度
+(float) heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width
{
    
    CGRect rect = [value boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)  options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil];
    
    return rect.size.height;
}

+ (float) heightForString:string andWidth:(float)width{
    
    UITextView *textView = [[UITextView alloc] init];
    textView.text = string;
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}

//字符串的行高度
+(NSMutableAttributedString *) setLineSpaceForString:(NSString *)value lineSpace:(float)lineSpace fontSize:(float)fontSize andTextColor:(UIColor *)color
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:value];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];//调整行间距
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [value length])];
    [attributedString addAttribute:NSForegroundColorAttributeName value:color range:NSMakeRange(0, value.length)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontSize] range:NSMakeRange(0, value.length)];
    
    return attributedString;
}

+ (NSMutableAttributedString *)attributedString:(NSString *)front fontColor:(UIColor *)frontColor frontFont:(UIFont *)frontFont behind:(NSString *)behind behindColor:(UIColor *)behindColor behindFont:(UIFont *)behindFont{
    
    NSMutableAttributedString *frontAttr = [[NSMutableAttributedString alloc]initWithString:front attributes:@{NSForegroundColorAttributeName:frontColor}];
    NSMutableAttributedString *behindAttr = [[NSMutableAttributedString alloc]initWithString:behind attributes:@{NSForegroundColorAttributeName:behindColor}];
    
    [frontAttr addAttribute:NSFontAttributeName value:frontFont range:NSMakeRange(0, front.length)];
    [behindAttr addAttribute:NSFontAttributeName value:behindFont range:NSMakeRange(0, behind.length)];
    [frontAttr appendAttributedString:behindAttr];
    return frontAttr;
}

+ (NSMutableAttributedString *)attributedString:(NSString *)front frontColor:(UIColor *)frontColor middle:(NSString *)middle middleColor:(UIColor *)middleColor behind:(NSString *)behind behindColor:(UIColor *)behindColor font:(UIFont *)font{
    
    NSMutableAttributedString *frontAttr = [[NSMutableAttributedString alloc]initWithString:front attributes:@{NSForegroundColorAttributeName:frontColor}];
    NSMutableAttributedString *middleAttr = [[NSMutableAttributedString alloc]initWithString:middle attributes:@{NSForegroundColorAttributeName:middleColor}];
    NSMutableAttributedString *behindAttr = [[NSMutableAttributedString alloc]initWithString:behind attributes:@{NSForegroundColorAttributeName:behindColor}];
    
    [frontAttr appendAttributedString:middleAttr];
    [frontAttr appendAttributedString:behindAttr];
    [frontAttr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, frontAttr.string.length)];
    return frontAttr;
}

//时间戳转对应的日期格式
- (NSString *)stringWithDateFormat:(NSString *)dateFormat
{
    //设置时间显示格式 
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:dateFormat];

    NSDate *date = nil;
    if (self.length == 10)
    {
        date = [NSDate dateWithTimeIntervalSince1970:self.longLongValue];
        
    }else//如果是13位时间戳则除以1000，iOS要求是10位的时间戳
    {
        date = [NSDate dateWithTimeIntervalSince1970:self.longLongValue/1000];
    }
    
    //将NSDate按格式转化为对应的时间格式字符串
    NSString *timesString = [formatter stringFromDate:date];
    
    return timesString;
}

- (NSString *)dateWithDateFormat:(NSString *) format
{
    @try {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:format];
        
        NSDate *needFormatDate = nil;
        if (self.length == 10)
        {
            needFormatDate = [NSDate dateWithTimeIntervalSince1970:self.longLongValue];
        }else//如果是13位时间戳则除以1000，iOS要求是10位的时间戳
        {
            needFormatDate = [NSDate dateWithTimeIntervalSince1970:self.longLongValue/1000];
        }
        NSInteger days = [needFormatDate daysAgo];
        double hours = [needFormatDate hoursAgo];
        double minutes = [needFormatDate minutesAgo];
    
        NSString *dateStr = @"";
        if (0 == days) {
            if (minutes<1) {  // 1分钟以内的
                dateStr = @"刚刚";
            }else if(minutes<60){  //  一个小时以内的
                dateStr = [NSString stringWithFormat:@"%d分钟前",(int)minutes];
            }else{
                if ([[NSDate date] day] - [needFormatDate day] == days) {
                    dateStr = [NSString stringWithFormat:@"%d小时前",(int)hours];
                }else{
                    [dateFormatter setDateFormat:@"HH:mm"];
                    dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
                }
            }
        }else if(1 == days){
            
            [dateFormatter setDateFormat:@"HH:mm"];
            if ([[NSDate date] day] - [needFormatDate day] == days) {
                dateStr = [NSString stringWithFormat:@"昨天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }else{
                dateStr = [NSString stringWithFormat:@"前天 %@",[dateFormatter stringFromDate:needFormatDate]];
            }
        }else if(2 == days && [[NSDate date] day] - [needFormatDate day] == days){
            [dateFormatter setDateFormat:@"HH:mm"];
            dateStr = [NSString stringWithFormat:@"前天 %@",[dateFormatter stringFromDate:needFormatDate]];
        }else{
            if ([[NSDate date] year] == [needFormatDate year]) {
                //  在同一年
                [dateFormatter setDateFormat:@"MM-dd HH:mm"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }else{
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
                dateStr = [dateFormatter stringFromDate:needFormatDate];
            }
        }
        return dateStr;
    }
    @catch (NSException *exception) {
        return @"";
    }
}

//验证邮箱
- (BOOL)isEmail
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

//验证手机号码
- (BOOL)isMobile
{
    //手机号以13、15、18开头，八个\d数字字符
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:self];
}

//验证用户名
- (BOOL)isUserName
{
    NSString *userRegex = @"^(([a-zA-Z]+)(([a-z0-9_]){5,25}$))";
    NSPredicate *userTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userRegex];
    return [userTest evaluateWithObject:self];
}

//验证url
- (BOOL)isUrlString
{
    NSString *userRegex = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSPredicate *userTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userRegex];
    return [userTest evaluateWithObject:self];
}

- (NSString *)md5
{
    const char *cStr = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    return[[NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1],
            result[2], result[3],
            result[4], result[5],
            result[6], result[7],
            result[8], result[9],
            result[10], result[11],
            result[12], result[13],
            result[14], result[15]
            ]
           lowercaseString];
}

//获取当前时间字符串
+ (NSString*)stringWithCurrentTimeString
{
    NSDateFormatter *dateformat = [[NSDateFormatter  alloc]init];
    [dateformat setDateFormat:@"yyyyMMddHHmmss"];
    return [dateformat stringFromDate:[NSDate date]];
}

+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

- (NSString *)urlEncode
{
    NSString *outputStr =(NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(__bridge CFStringRef)self,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
    return outputStr;
}

- (NSString *)urlDecode
{
    NSMutableString *outputStr = [NSMutableString stringWithString:self];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0,outputStr.length)];
    return
    [outputStr stringByRemovingPercentEncoding];
}

- (NSString *)replaceStringWithAsterisStartLocation:(NSInteger)startLocation length:(NSInteger)length
{
    NSString *newStr = self;
    for (int i = 0; i < length; i++)
    {
        NSRange range = NSMakeRange(startLocation, 1);
        newStr = [newStr stringByReplacingCharactersInRange:range withString:@"*"];
        startLocation ++;
    }
    return newStr;
}

- (NSString *)removeAllDigits
{
    NSMutableString *noDigitsString = [NSMutableString new];
    for (NSUInteger i = 0; i < self.length; i++)
    {
        unichar characterToAdd = [self characterAtIndex:i];
        if(!isdigit(characterToAdd))
        {
            NSString *stringToAdd = [NSString stringWithCharacters:&characterToAdd length:1];
            [noDigitsString appendString:stringToAdd];
        }
    }
    [noDigitsString replaceOccurrencesOfString:@"." withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, noDigitsString.length)];
    return noDigitsString;
}


+ (BOOL)valiMobile:(NSString *)mobile{
    if (mobile.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
     * 移动号段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     * 联通号段: 130,131,132,145,155,156,170,171,175,176,185,186
     * 电信号段: 133,149,153,170,173,177,180,181,189
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     */
    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,145,155,156,170,171,175,176,185,186
     */
    NSString *CU = @"^1(3[0-2]|4[5]|5[56]|7[0156]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,149,153,170,173,177,180,181,189
     */
    NSString *CT = @"^1(3[3]|4[9]|53|7[037]|8[019])\\d{8}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobile] == YES)
        || ([regextestcm evaluateWithObject:mobile] == YES)
        || ([regextestct evaluateWithObject:mobile] == YES)
        || ([regextestcu evaluateWithObject:mobile] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
+ (BOOL)isCorrect:(NSString *)IDNumber
{
    NSMutableArray *IDArray = [NSMutableArray array];
    if (IDNumber.length != 18) {
        return NO;
    }
    // 遍历身份证字符串,存入数组中
    for (int i = 0; i < IDNumber.length; i++) {
        NSRange range = NSMakeRange(i, 1);
        NSString *subString = [IDNumber substringWithRange:range];
        [IDArray addObject:subString];
    }
    // 系数数组
    NSArray *coefficientArray = [NSArray arrayWithObjects:@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2", nil];
    // 余数数组
    NSArray *remainderArray = [NSArray arrayWithObjects:@"1", @"0", @"X", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2", nil];
    // 每一位身份证号码和对应系数相乘之后相加所得的和
    int sum = 0;
    for (int i = 0; i < 17; i++) {
        int coefficient = [coefficientArray[i] intValue];
        int ID = [IDArray[i] intValue];
        sum += coefficient * ID;
    }
    // 这个和除以11的余数对应的数
    NSString *str = remainderArray[(sum % 11)];
    // 身份证号码最后一位
    NSString *string = [IDNumber substringFromIndex:17];
    // 如果这个数字和身份证最后一位相同,则符合国家标准,返回YES
    if ([str isEqualToString:string]) {
        return YES;
    } else {
        return NO;
    }
}
@end
